package dao;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.NoResultException;
import javax.persistence.TypedQuery;

import entity.User;

@JPA
@Stateless
public class JPAUserDAO extends GenericJPADAO<User> implements UserDAO {

	@Override
	public User selectUserByName(String name) {
		TypedQuery<User> query = em.createNamedQuery("User.selectByName", User.class).setParameter("name", name);
		User res = null;
		try {
			res = query.getSingleResult();
		} catch(NoResultException nre) { }
		return res;		
	}
	
	@Override
	public Long selectRolesCountByUserName(String userName) {
		TypedQuery<Long> query = em.createNamedQuery(
				"User.selectRolesCountByUserName", Long.class).setParameter("name", userName);
		return query.getSingleResult();
	}
	
	@Override
	public List<User> selectUsersByPartName(String partName) {
		TypedQuery<User> query = em.createNamedQuery(
				"User.selectByPartName", User.class).setParameter("partname", "%" + partName + "%");
		return query.getResultList();
	}
	
	@Override
	public List<User> selectUserListByRoleAndUserPartName(String roleName, String partName) {
		TypedQuery<User> query = em.createNamedQuery(
				"User.selectByRoleAndUserPartName", User.class)
				.setParameter("roleName", roleName).setParameter("partname", "%" + partName + "%");
		return query.getResultList();		
	}
	
	@Override
	public List<User> selectUserListByUserPartNameWithNoRoles(String partName) {
		TypedQuery<User> query = em.createNamedQuery(
				"User.selectUserListByUserPartNameWithNoRoles", User.class)
				.setParameter("partname", "%" + partName + "%");
		return query.getResultList();		
	}
	
}
